package com.example.demo.controller;

import com.example.demo.model.Student;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.*;

@Controller
@RequestMapping("student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("list")
    public String list(ModelMap map, Student student) {
        if ("".equals(student.getName())) {
            student.setName(null);
        }
        map.put("studentList", studentService.findAll(student));
        return "student/list";
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable String id) {
        studentService.deleteById(id);
        return "redirect:/student/list";
    }

    @RequestMapping("create")
    public String create() {
        return "student/create";
    }

    @RequestMapping("save")
    public String save(Student s) {
        if (s.getId() == null) {
            s.setId(UUID.randomUUID().toString());
        }
        studentService.save(s);
        return "redirect:/student/list";
    }

    @RequestMapping("update/{id}")
    public String update(@PathVariable String id, ModelMap map) {
        Student s = studentService.getReferenceById(id);
        map.put("student", s);
        return "student/update";
    }
}
